package com.ccc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ccc.dao.AdDao;
import com.ccc.model.Ad;
import com.ccc.model.Product;
import com.ccc.model.User;
import com.ccc.util.dao.UtilDao;

@Component("adDao")
public class AdDaoImpl implements AdDao {
	private UtilDao utilDao;
	
	@Override
	public void addAd(Ad ad) {
		utilDao.save(ad);
	}

	@Override
	public void deleteAd(Ad ad) {
		utilDao.delete(ad);
	}

	@Override
	public void updateAd(Ad ad) {
		utilDao.update(ad);
	}

	public UtilDao getUtilDao() {
		return utilDao;
	}
	@Resource
	public void setUtilDao(UtilDao utilDao) {
		this.utilDao = utilDao;
	}

	@Override
	public Ad findAdById(Integer id) {
		return utilDao.find(Ad.class, id);
	}

	@Override
	public List<Ad> findAds(User user, Integer currenttime) {
		return utilDao.find("from Ad a where a.user = ? and a.currentTime = ?", new Object[]{user,currenttime});
	}

	@Override
	public Ad findAd(User user, Product product, Integer currenttime) {
		List<Ad> list = utilDao.find("from Ad a where a.user = ? and a.currentTime = ? and a.product = ?", new Object[]{user,currenttime,product});
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Ad> findAds(User user) {
		return utilDao.find("from Ad a where a.user = ?", new Object[]{user});
	}

	@Override
	public List<Ad> findAdsByTime(Integer currenttime) {
		return utilDao.find("from Ad a where a.currentTime = ?", new Object[]{currenttime});
	}

	@Override
	public List<Ad> findAll() {
		return utilDao.find("from Ad a", null);
	}

	@Override
	public Long SumAmount(Integer currenttime) {
		return utilDao.sum("select SUM(a.adPrice) from Ad a where a.currentTime = ?", new Object[]{currenttime});
	}

	@Override
	public Long SumAmount(Integer currenttime, User user) {
		return utilDao.sum("select SUM(a.adPrice) from Ad a where a.currentTime = ? and a.user = ?", new Object[]{currenttime, user});
	}

	@Override
	public Long SumAmount(Product product, Integer currenttime) {
		return utilDao.sum("select SUM(a.adPrice) from Ad a where a.currentTime = ? and a.product = ?", new Object[]{currenttime, product});
	}
	
	@Override
	public Long SumAmountEarlierTime(Product product, Integer currenttime) {
		return utilDao.sum("select SUM(a.adPrice) from Ad a where a.currentTime <= ? and a.product = ?", new Object[]{currenttime, product});
	}

	@Override
	public Long SumAmount(User user,Product product) {
		return utilDao.sum("select SUM(a.adPrice) from Ad a where a.user = ? and a.product = ?", new Object[]{user, product});
	}
}
